/**
 * @author fan.donqqing 
 */
package o2o.hx.cron.core.zookeeper.lock;

import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import o2o.hx.cron.core.job.excutor.TaskExcutor;

public class ReenTrenZkLock {

	private final InterProcessMutex lock;
	private final String clientName;

	/**
	 *  @param client ZK client
	 *  @param root 根目录
	 *  @param subDir 希望锁定的子目录
	 *  @param clientName 客户端名称
	 */
	public ReenTrenZkLock(CuratorFramework client, String root, String subDir, String clientName) {
		super();
		this.clientName = clientName;
		this.lock = new InterProcessMutex(client, root+subDir);
	}
	
	/**
	 *  @param client ZK client
	 *  @param lockPath 希望锁定的子目录
	 *  @param clientName 客户端名称
	 */
	public ReenTrenZkLock(CuratorFramework client, String lockPath, String clientName) {
		super();
		this.clientName = clientName;
		this.lock = new InterProcessMutex(client, lockPath);
	}

	/**
	 * 	锁定目录，执行对应任务
	 *  @param client ZK client
	 *  @param lockPath 希望锁定的子目录
	 *  @param clientName 客户端名称
	 */
	public void doTask(long time, TimeUnit unit,TaskExcutor  task) throws Exception {
		if (!lock.acquire(time, unit)) {
			throw new IllegalStateException(clientName + " could not acquire the lock");
		}
		try {
			task.excutor();
			System.out.println(clientName + " has the lock");
		} finally {
			System.out.println(clientName + " releasing the lock");
			// always release the lock in a finally block
			lock.release();
		}
	}

}
